package com.qinglei.recoup.system.service.impl;

import com.aliyun.iot20180120.models.CreateOTAStaticUpgradeJobResponseBody;
import com.aliyun.iot20180120.models.ListOTAFirmwareResponseBody;
import com.aliyun.iot20180120.models.ListOTATaskByJobResponseBody;
import com.aliyun.iot20180120.models.QueryOTAJobResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qinglei.recoup.common.domain.CommonConstant;
import com.qinglei.recoup.common.service.RedisService;
import com.qinglei.recoup.common.service.impl.ProductCache;
import com.qinglei.recoup.system.domain.RadarUpVersionVo;
import com.qinglei.recoup.system.domain.VersionJob;
import com.qinglei.recoup.system.dao.VersionJobMapper;
import com.qinglei.recoup.system.enums.IocUpdateEnum;
import com.qinglei.recoup.system.service.BedService;
import com.qinglei.recoup.system.service.RadarService;
import com.qinglei.recoup.system.service.VersionJobService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author cxd
 */
@Slf4j
@Service
public class VersionJobServiceImpl extends ServiceImpl<VersionJobMapper, VersionJob> implements VersionJobService {

    @Resource
    private BedService bedService;
    @Resource
    private ProductCache productCache;
    @Resource
    private RadarService radarService;
    @Autowired
    private RedisService redisService;

    @Value("${iot.upgrade.productKey}")
    private String productKey;
    @Value("${iot.upgrade.destVersion}")
    private String destVersion;

    @Override
    public void updateRadarVersion() {
        log.info("updateRadarVersion run");
        //查询当前需要更新的设备信息
        List<RadarUpVersionVo> radarUpVersionVoList = bedService.getOnlineRadarList(productKey,destVersion);
        if (CollectionUtils.isEmpty(radarUpVersionVoList)) {
            return;
        }
        //查询固件列表
        ListOTAFirmwareResponseBody.ListOTAFirmwareResponseBodyFirmwareInfo oTAFirmwareResponse
                = productCache.selectOTAFirmwareList(productKey, destVersion);
        if (null == oTAFirmwareResponse || null == oTAFirmwareResponse.getSimpleFirmwareInfo()) {
            log.info("updateRadarVersion 获取查询固件列表为空");
            return;
        }
        String firmwareId = "";
        List<ListOTAFirmwareResponseBody.ListOTAFirmwareResponseBodyFirmwareInfoSimpleFirmwareInfo> simpleFirmwareInfo = oTAFirmwareResponse.getSimpleFirmwareInfo();
        for (ListOTAFirmwareResponseBody.ListOTAFirmwareResponseBodyFirmwareInfoSimpleFirmwareInfo oTAFirmwareResponseInfo : simpleFirmwareInfo) {
            if ("MCU".equals(oTAFirmwareResponseInfo.getModuleName()) && destVersion.equals(oTAFirmwareResponseInfo.getDestVersion())) {
                firmwareId = oTAFirmwareResponseInfo.getFirmwareId();
            }
        }
        if (StringUtils.isEmpty(firmwareId)) {
            log.info("updateRadarVersion 获取firmwareId失败");
            return;
        }
        //200条数据分为一组
        List<List<RadarUpVersionVo>> partition = ListUtils.partition(radarUpVersionVoList, 200);
        for (List<RadarUpVersionVo> radarUpVersionVos : partition) {
            this.radarDataHandle(productKey,firmwareId,radarUpVersionVos);
        }
    }
    private void radarDataHandle(String productKey, String firmwareId,List<RadarUpVersionVo> radarUpVersionVos){
        ArrayList<String> deviceSnList = new ArrayList<>();
        radarUpVersionVos.forEach(item->{
            deviceSnList.add(item.getDeviceSn());
        });
        CreateOTAStaticUpgradeJobResponseBody.CreateOTAStaticUpgradeJobResponseBodyData otaStaticUpgradeJob
                = productCache.createOTAStaticUpgradeJob(productKey, firmwareId, deviceSnList);
        if (null == otaStaticUpgradeJob){
            deviceSnList.forEach(item->{
                radarService.updateVersionAndStatusBySn(item,destVersion,null);
            });
            log.info("updateRadarVersion 创建任务更新任务ID为空");
            return;
        }
       //通过JOBid查询出发送成功的设备
        ListOTATaskByJobResponseBody.ListOTATaskByJobResponseBodyData oTATaskByJobResponseBodyData = productCache.selectOTATaskByJobList(otaStaticUpgradeJob.getJobId());
        if(null == oTATaskByJobResponseBodyData){
            log.info("updateRadarVersion selectSendSuccessSn为空,JOBID为:{}",otaStaticUpgradeJob.getJobId());
            return;
        }
        List<ListOTATaskByJobResponseBody.ListOTATaskByJobResponseBodyDataSimpleOTATaskInfo> simpleOTATaskInfoList = oTATaskByJobResponseBodyData.getSimpleOTATaskInfo();
        if(CollectionUtils.isEmpty(simpleOTATaskInfoList)){
            log.info("updateRadarVersion simpleOTATaskInfo为空:{}",otaStaticUpgradeJob.getJobId());
            return;
        }
        Map<String, ListOTATaskByJobResponseBody.ListOTATaskByJobResponseBodyDataSimpleOTATaskInfo> simpleOTATaskInfoListCollect
                = simpleOTATaskInfoList.stream().collect(Collectors.toMap(ListOTATaskByJobResponseBody.ListOTATaskByJobResponseBodyDataSimpleOTATaskInfo::getDeviceName, Function.identity()));
        //设备状态缓存redis
        deviceSnList.forEach(item->{
            try {
                if(simpleOTATaskInfoListCollect.containsKey(item)){
                    redisService.hset(CommonConstant.JOBIDCACHE_RADAR_STATUS,item, IocUpdateEnum.IN_PROGRESS.getCode());
                    radarService.updateVersionAndStatusBySn(item,simpleOTATaskInfoListCollect.get(item).getDestVersion(),2);
                }else {
                    radarService.updateVersionAndStatusBySn(item,destVersion,null);
                }
            }catch (Exception e){
                log.error("updateRadarVersion error sn:{}", item, e);
            }
        });
        VersionJob versionJob = new VersionJob();
        String jobId = otaStaticUpgradeJob.getJobId();
        versionJob.setJobId(jobId);
        versionJob.setFirmwareId(firmwareId);
        versionJob.setProductKey(productKey);
        versionJob.setStatus(0);
        baseMapper.insert(versionJob);
    }

    @Override
    public void queryAndUpdateStatus() {
        List<VersionJob> versionJobList = baseMapper.selectList(new QueryWrapper<VersionJob>().lambda().eq(VersionJob::getStatus, 0));
        if(CollectionUtils.isEmpty(versionJobList)){
            return;
        }
        versionJobList.forEach(item->{
            //任务执行完成后，查询当前各个设备的状态
            ListOTATaskByJobResponseBody.ListOTATaskByJobResponseBodyData oTATaskByJobResponseBodyData = productCache.selectOTATaskByJobList(item.getJobId());
            if(null!= oTATaskByJobResponseBodyData){
                List<ListOTATaskByJobResponseBody.ListOTATaskByJobResponseBodyDataSimpleOTATaskInfo> simpleOTATaskInfoList = oTATaskByJobResponseBodyData.getSimpleOTATaskInfo();
                simpleOTATaskInfoList.forEach(simpleOTATaskInfo->{
                    //更新设备的状态
                    try {
                        String version = simpleOTATaskInfo.getSrcVersion();
                        Integer status = null;
                        if(IocUpdateEnum.SUCCEEDED.getCode().equals(simpleOTATaskInfo.getTaskStatus())||IocUpdateEnum.FAILED.getCode().equals(simpleOTATaskInfo.getTaskStatus())){
                            status =1;
                            redisService.hset(CommonConstant.JOBIDCACHE_RADAR_STATUS,simpleOTATaskInfo.getDeviceName(), simpleOTATaskInfo.getTaskStatus());
                            version = simpleOTATaskInfo.getDestVersion();
                        }
                        radarService.updateVersionAndStatusBySn(simpleOTATaskInfo.getDeviceName(),version,status);
                    }catch (Exception e){
                        log.error("queryAndUpdateStatus error sn:{}", simpleOTATaskInfo.getDeviceName(), e);
                    }
                });
            }
            //查询指定升级批次的详情
            QueryOTAJobResponseBody.QueryOTAJobResponseBodyData queryOTAJobResponseBodyData = productCache.selectOTAJobRequest(item.getJobId());
            if(null !=queryOTAJobResponseBodyData && "COMPLETED".equals(queryOTAJobResponseBodyData.getJobStatus())){
                //更新一下job状态
                VersionJob versionJob = new VersionJob();
                versionJob.setStatus(1);
                baseMapper.update(versionJob,new QueryWrapper<VersionJob>().lambda().eq(VersionJob::getJobId,item.getJobId()));
            }
        });
    }
}
